<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Models\TaskClass;
use App\Models\TaskClassModule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TaskclassController extends Controller
{

    private $typeArr = array(
        1 => '文本框',
        2 => '下拉框',
        3 => '时间',
        4 => '文件上传',
        5 => '文本域',
    );

    protected $request;
    protected $model;
    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model = new TaskClass();
    }

    /**
     * 任务模板分类
     * @param Request $request
     */
    public function index(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            $this->back('接收值为空');
        }
        $fid            = isset($data['fid']) ? $data['fid'] : 0;
        $taskClassModel = new \App\Models\TaskClass();
        $taskClassPage  = $taskClassModel->where('fid', $fid)->orderBy('id', 'desc')->paginate($data['page_count']);
        $taskList       = [];
        if (!$taskClassPage->isEmpty() && $taskClassPage[0]['level'] == 3) {
            $taskIds  = $taskClassPage->pluck('task_id')->toArray();
            $taskList = Db::table('tasks')->select(['id', 'name'])->where('id', array_unique($taskIds))->get()->keyBy('id');
        }

        //判断有无子集
        $ids   = $taskClassPage->pluck('id');
        $child = $taskClassModel::query()->whereIn('fid', $ids)->get()->keyBy('fid');

        foreach ($taskClassPage as $item) {
            $item['task_name'] = isset($taskList[$item['task_id']]) ? $taskList[$item['task_id']]->name : '';
            $item['is_child']  = isset($child[$item['id']]);
        }

        $this->back('获取成功', '200', $taskClassPage);
    }

    public function getTaskClassList()
    {
        $params = $this->request->all();
        $result = $this->model->getTaskClassList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }


    /**
     * 任务模板分类
     * @param Request $request
     */
    public function class_list(Request $request)
    {

        $data = $request->all();
        if (empty($data)) {
            $this->back('接收值为空');
        }

        $TaskClassModel = new \App\Models\TaskClass();
        $TaskClassPage = $TaskClassModel->all();
        $this->back('获取成功', '200', $TaskClassPage);
//            $this->back($return);

    }


    /**
     * 添加
     * @param Request $request
     */
    public function add(Request $request)
    {
        $data = $request->all();
        // var_dump($data);
        $add = array();
        $checkModel = new \App\Models\TaskClass();
        if (isset($data['title']) && $data['title'] != '') {
            $add['title'] = $data['title'];
            $checkModel = $checkModel->where('title', $data['title']);
        } else {
            $this->back('请填写分类');
        }
        if (isset($data['fid']) && $data['fid'] >= 0) {
            $add['fid'] = $data['fid'];
        } else {
            $this->back('请填写父id');
        }
        if (isset($data['level']) && in_array($data['level'], [1, 2,3])) {
           $add['level'] = $data['level'];
        } else {
            $this->back('请填分类等级');
        }
        if (isset($data['organize_id']) && $data['organize_id']) {
            $add['organize_id'] = $data['organize_id'];
        }
        if ($data['level'] == 3 && !isset($add['organize_id'])) {
            $this->back('三级分类部门必选');
        }
        if (isset($data['warehouse_id']) && $data['warehouse_id'] > 0) {
            $add['warehouse_id'] = $data['warehouse_id'];
        }
        if (isset($data['type_detail']) && $data['type_detail'] > 0) {
            $add['type_detail'] = $data['type_detail'];
        }
        if (isset($data['user_id']) && !empty($data['user_id'])) {
            $add['user_id'] = implode(',',$data['user_id']);
        }

        if (isset($data['ext'])) {

            foreach ($data['ext'] as $item) {

                if (!isset($item['name'])) {
                    $this->back('请填写模块字段');
                }

                if (!preg_match("/^[a-zA-Z_\s]+$/", $item['name'])) {
                    $this->back('模块字段只能英文格式和下划线');
                }

                if (!isset($item['label'])) {
                    $this->back('请填写模块名称');
                }
                if (!isset($item['type'])) {
                    $this->back('请选择模块类型');
                }
                if (isset($item['api'])) {
                    if (!isset($item['api_id'])) {
                        $this->back('api接口需要api_id');
                    }
                    if (!isset($item['api_label'])) {
                        $this->back('api接口需要api_label');
                    }
                }

                if ($item['type'] == 2) {
                    if (!isset($item['api']) || $item['api'] == null || $item['api'] == '') {
                        $this->back('下拉框需要api路径');
                    }
                    if (!isset($item['api_id']) || $item['api_id'] == null || $item['api_id'] == '') {
                        $this->back('下拉框需要api_id');
                    }
                    if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_id'])) {
                        $this->back('下拉框api_id只能英文格式和下划线');
                    }
                    if (!isset($item['api_label']) || $item['api_label'] == null || $item['api_label'] == '') {
                        $this->back('下拉框需要api_label');
                    }
                    if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_label'])) {
                        $this->back('下拉框api_label只能英文格式和下划线');
                    }
                }


            }
        }

        $has = $checkModel->first();
        if (isset($has['id'])) {
            $this->back('数据已经存在');
        }
        $id = \App\Models\TaskClass::insertGetId($add);
        if ($id > 0) {
            if (isset($data['ext'])) {
                foreach ($data['ext'] as $item) {
                    $add = array();
                    $add['class_id'] = $id;
                    $add['name'] = $item['name'];
                    $add['label'] = $item['label'];
                    $add['type'] = $item['type'];
                    if (isset($item['api'])) {
                        $add['api'] = $item['api'];
                    }
                    if (isset($item['api_id'])) {
                        $add['api_id'] = $item['api_id'];
                    }
                    if (isset($item['api_label'])) {
                        $add['api_label'] = $item['api_label'];
                    }
                    if (isset($item['api_param'])) {
                        $add['api_param'] = $item['api_param'];
                    }
                    TaskClassModule::insertGetId($add);
                }
            }
            $this->back('添加成功', '200');
        } else {
            $this->back('添加失败');
        }
    }

    public function saveTaskClass(Request $request)
    {
        $params = $this->request->all();
        $result = $this->model->saveTaskClass($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     *  修改
     * @param Request $request
     */
    public function update(Request $request)
    {
        $data = $request->all();
//        dump($data);exit;
        $ApiPlan = \App\Models\TaskClass::where('id', $data['id'])->first();
        if (!isset($ApiPlan['id'])) {
            $this->back('分类不存在');
        }


        if (isset($data['ext'])) {

            foreach ($data['ext'] as $item) {

                if (!isset($item['name'])) {
                    $this->back('请填写模块字段');
                }
                if (!preg_match("/^[a-zA-Z_\s]+$/", $item['name'])) {
                    $this->back('模块字段只能英文格式和下划线');
                }
                if (!isset($item['label'])) {
                    $this->back('请填写模块名称');
                }
                if (!isset($item['type'])) {
                    $this->back('请选择模块类型');
                }
                if (isset($item['api'])) {
                    if (!isset($item['api_id'])) {
                        $this->back('api接口需要api_id');
                    }
                    if (!isset($item['api_label'])) {
                        $this->back('api接口需要api_label');
                    }
                }
                if ($item['type'] == 2) {
                    if (!isset($item['api']) || $item['api'] == null || $item['api'] == '') {
                        $this->back('下拉框需要api路径');
                    }
                    if (!isset($item['api_id']) || $item['api_id'] == null || $item['api_id'] == '') {
                        $this->back('下拉框需要api_id');
                    }
                    if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_id'])) {
                        $this->back('下拉框api_id只能英文格式和下划线');
                    }
                    if (!isset($item['api_label']) || $item['api_label'] == null || $item['api_label'] == '') {
                        $this->back('下拉框需要api_label');
                    }
                    if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_label'])) {
                        $this->back('下拉框api_label只能英文格式和下划线');
                    }
                }
            }
        }

        $update['title'] = $data['title'];
        isset($data['organize_id']) && $update['organize_id'] = $data['organize_id'];
        isset($data['warehouse_id']) && $update['warehouse_id'] = $data['warehouse_id'];
        isset($data['type_detail']) && $update['type_detail'] = $data['type_detail'];

        $updateResult = \App\Models\TaskClass::where('id', $data['id'])->update($update);

        if (isset($data['ext']) && !empty($data['ext'])) {
            TaskClassModule::where('class_id', $data['id'])->delete();
            foreach ($data['ext'] as $item) {
                $edit = array();
                $edit['class_id'] = $data['id'];
                $edit['name'] = $item['name'];
                $edit['label'] = $item['label'];
                $edit['type'] = $item['type'];
                if (isset($item['api'])) {
                    $edit['api'] = $item['api'];
                }
                if (isset($item['api_id'])) {
                    $edit['api_id'] = $item['api_id'];
                }
                if (isset($item['api_label'])) {
                    $edit['api_label'] = $item['api_label'];
                }
                if (isset($item['api_param'])) {
                    $edit['api_param'] = $item['api_param'];
                }
                TaskClassModule::insertGetId($edit);
            }
        }

        if ($updateResult > 0) {  //》0
            $this->back('编辑成功', '200');
        } else { //==0
            $this->back('修改成功', '200');
        }

    }

    /**
     * 分类模块
     * @param Request $request
     */
    public function module(Request $request)
    {
        $data = $request->all();
        $TaskClassModule = TaskClassModule::where('class_id', $data['id'])->get()->toArray();

        foreach ($TaskClassModule as &$item) {
            $item['type_show'] = $this->typeArr[$item['type']];
        }

        $this->back('获取成功', '200', $TaskClassModule);
    }


    /**
     * 添加模块
     * @param Request $request
     */
    public function addmodule(Request $request)
    {
        $data = $request->all();
        $add = array();
        $checkModel = new \App\Models\TaskClassModule();
        if (isset($data['name']) && $data['name'] != '') {
            $add['name'] = $data['name'];
            $checkModel = $checkModel->where('title', $data['title']);
        } else {
            $this->back('请填写模块字段');
        }

        // $has = $checkModel->where('class_id',$data['id'])->first();
        if (isset($has['id'])) {
            $this->back('数据已经存在');
        }
        $id = \App\Models\TaskClass::insertGetId($add);
        if ($id > 0) {
            $this->back('添加成功', '200');
        } else {
            $this->back('添加失败');
        }
    }


    public function info(Request $request)
    {

        $data = $request->all();
        $TaskClass = TaskClass::where('id', $data['id'])->first();
        $this->back('获取成功', '200', $TaskClass);

    }


    public function del(Request $request)
    {
        $data = $request->all();
        $task = \App\Models\TaskModel::where('class_id', $data['id'])->first();
        if (isset($task['class_id'])) {
            $this->back('任务中有用此分类，无法删除');
        }

        $exists = TaskClass::where('fid', $data['id'])->first();
        if ($exists) {
            $this->back('有子分类，无法删除');
        }


        $TaskClass = TaskClass::where('id', $data['id'])->delete();
        $this->back('删除成功', '200', $TaskClass);

    }

    public function deleteTaskClass()
    {
        $params = $this->request->all();
        $result = $this->model->deleteTaskClass($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }


    /**
     * 分类绑定模板
     */
    public function template_binding(Request $request)
    {
        $data           = $request->all();
        $taskId         = $data['task_id'];
        $classId        = $data['class_id'];
        $TaskClassModel = new \App\Models\TaskClass();

        $info  = $TaskClassModel->where('id', $classId)->first();

        if (!$info) {
            $this->back('分类不存在');
        }
        if ($info['level'] != 3) {
            $this->back('三级分类才需绑定模板');
        }

        $result = $TaskClassModel->where('id', $classId)->update(['task_id' => $taskId]);
        if (!$result) {
            $this->back('模板绑定失败');
        }

        $this->back('模板绑定成功', '200');
    }

    /**
     * 获取搜索下拉框
     * @param Request $request
     */
    public function getSelect(Request $request)
    {
        $params = $request->all();
        $list = db::table('task_class as a');
        if (isset($params['is_task'])){
            $list = $list->where('is_task', $params['is_task']);
        }
        $list = $list
            ->select('*')
            ->get()
            ->toArrayList();
        $list = array_column($list, null, 'id');
        $taskMoudle = db::table('tasks')
            ->where('type', 2)
            ->get()
            ->keyBy('class_id');
        foreach ($list as $k => $v) {
            $list[$k]['task_id'] = $taskMoudle[$v['id']]->Id ?? 0;
            if ($v['level'] == 3) {
                if (isset($list[$v['fid']])) {
                    $list[$k]['task_id'] = $taskMoudle[$v['id']]->Id ?? 0;
                    $list[$v['fid']]['children'][] = $v;
                    unset($list[$k]);
                }
            }
        }

        foreach ($list as $k => $v) {
            if ($v['level'] == 2) {
                if (isset($list[$v['fid']])) {
                    $list[$k]['task_id'] = $taskMoudle[$v['id']]->Id ?? 0;
                    $list[$v['fid']]['children'][] = $v;
                    unset($list[$k]);
                }
            }
        }
        $this->back('获取成功', '200', array_values($list));
    }


}
